package org.pb.org.service.impl;

import org.pb.basic.service.impl.BaseServiceImpl;
import org.pb.org.domain.Department;
import org.pb.org.mapper.DepartmentMapper;
import org.pb.org.query.DepartmentQuery;
import org.pb.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 部门对应的业务层实现类
 * @author
 */
@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department, DepartmentQuery> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public void save(Department department) {
        // 获取到上级部门的id属性
        Long mId = department.getParent_department().getId();
        // 声明一个部门层级变量,初始化赋值为null
        String deptPath = null;
        // 判断当前的新增信息中是否由上级部门id
        if (mId != null) {
            // 如果不为空，则获取到对应上级部门的数据
            Department mDept= departmentMapper.loadById(mId);
            // 将参数的parent_id值设置为上局部门的id
            department.setParent_id(mId);
            // 将上级部门的dirPath赋予给当前部门的层级变量
            deptPath = mDept.getDirPath();
        }
        // 执行添加命令
        departmentMapper.save(department);
        // 获取到自增长id的值，并拼接到当前部门层级变量后
        deptPath = deptPath + "/" + department.getId().toString();
        // 修改department的部门层级
        department.setDirPath(deptPath);
        // 执行修改操作，将当前的部门层级修改为当前部门层级
        departmentMapper.updateDirPath(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        // 获取到参数中的上级部门的id
        Long mId = department.getParent_department().getId();
        // 设置当前部门层级字符串
        String localPath = "/" + department.getId();
        String dirPath = null;
        // 判断上级部门id是否为空
        if (mId == null) {
            // 如果为空，则将参数的dirPath修改当前部门的id
            department.setDirPath(localPath);
        } else if (mId == department.getId()) {
            // 如果上级部门id为自己的id，那么抛出异常
            throw new RuntimeException("上级部门只能为空或其他部门，不能为当前部门");
        } else {
            // 如果不为空，则获取到上级部门的dirPath数据
            dirPath = departmentMapper.loadById(mId).getDirPath();
        }
        // 判断上级部门的dirPath和当前上级部门的dirPath是否相同
        if (!department.getDirPath().replaceAll(localPath, "").equals(dirPath)) {
            // 如果不相同，则需要修改上级部门层级内容
            dirPath = dirPath + "/" + department.getId().toString();
            department.setDirPath(dirPath);
            // 将上级部门id修改为当前的上级部门id
            department.setParent_id(mId);
        }
        // 如果相同，则证明部门层级未发生改变，不需要
        departmentMapper.update(department);
    }

    @Override
    public List<Department> findTree() {
        return departmentMapper.findTree();
    }

}
